/**
 *  Google Picasa Web Album
 *  @version 1.0.3 build 2012.7.25
 *  @author  Mr.Asong
 *  @email   i@mrasong.com
 *  @link    http://mrasong.com
 *
 *
 * 1.0.3 build 2012.7.25
 * 修改相册列表页面，点击图片为打开此相册。
 *
 * 1.0.1 build 2012.6.26
 */
(function($){
$.extend({
	pwa: {
		version: '1.0.3',
		author: 'Mr.Asong',
		link: 'http://mrasong.com',
		defaults: {
			title: 'Google Picasa Web Album',
			subtitle: 'My Album',
			userid: '105067663123386047324', //Google帐号或Google userid，如果是Gmail可以省去后缀如 username@gmail.com，可以直接写username
			showid: 'pwa_album', //显示内容div
			pagesize: 20, //每页显示图片数量
			offset: 0, //返回顶部的高度
			size: { small:160, middle:800, big:1600 }, //图片像素, 小->大  94, 110, 128, 200, 220, 288, 320, 400, 512, 576, 640, 720, 800, 912, 1024, 1152, 1280, 1440, 1600
			tips: null , //提示
			footer: '<span><a href="http://mrasong.com/">&copy Mr.Asong</a></span>' ,
			lang: {
				loading: '正在加载中...',
				home: '首页',
				tit_tips_album: '点击打开相册',
				tit_tips_photo: '点击查看图片详情',
				navfirst: '首页',
				navprevious: '上一页',
				navnext: '下一页',
				navlast: '末页',
				navinfo: '共{$2}页，第{$1}页',
				exifs: '照片Exifs信息：'
			}
		},
		/********************************************************************************/
		
		htmls: { /* html */
			clear: function(){ 
				return '<div class="pwa_clear"></div>'; 
			},
			
			wrap: function(){ 
				/* header */
				str = '<div id="pwa_tips" style="display:none;">'+ $.pwa.defaults.lang.loading +'</div>';
				str += '<div id="pwa_header">';
				if( $.pwa.defaults.title != null ){
					str += '<h1><a href="#">'+ $.pwa.defaults.title +'</a></h1>';
					str += '<p>'+ $.pwa.defaults.subtitle +'</p>';
				}
				/* crumbs */
				str += '<div class="pwa_crumbs"><span class="pwa_crumbs_index"></span>';
				str += '<span class="pwa_crumbs_album"></span><span class="pwa_crumbs_photo"></span></div>';
				str += '</div>';
				/* content */
				str += '<div id="pwa_content"><div id="pwa_album_list" class="pwa_album_list"></div>';
				str += '<div id="pwa_album_photo" style="display:none;"></div></div>';
				/* footer */
				if( $.pwa.defaults.footer != null ){
					str += '<div id="pwa_footer"><p>'+ $.pwa.defaults.footer +'</div>';
				}
				return str ;
			},
			
			img: function(type, src, title){ /* 生成图片html */
				if( type == "list" ){
					img_small = src + '?mrasong.com=&imgmax='+$.pwa.defaults.size.small ;
					src = src + '?mrasong.com=&imgmax='+$.pwa.defaults.size.big ;
				}else if( type=="photo" ){
					img_small = src + '?mrasong.com=&imgmax='+$.pwa.defaults.size.middle ;
					src = src + '?mrasong.com=&imgmax='+$.pwa.defaults.size.big ;
				}else{
					img_small = type;
					src = src + '?mrasong.com=&imgmax='+$.pwa.defaults.size.big ;
				}
				return '<a href="'+ src +'" title="'+ title +'"><img src="'+ img_small +'" alt="'+ title +'" /></a>';
			},

			nav: function(item, page){ /* 显示首页分页按钮 */
				page = parseInt(page);
				var total = item.gphoto$numphotos.$t; //照片总数
				var album_id = item.gphoto$id.$t; //相册id
				var pages = Math.ceil(total/$.pwa.defaults.pagesize); //总页数
				var navs = [$.pwa.defaults.lang.navfirst, $.pwa.defaults.lang.navprevious, $.pwa.defaults.lang.navnext, $.pwa.defaults.lang.navlast, $.pwa.defaults.lang.navinfo];
				var clickfun = '$.pwa.func.showPicList';
				var str = "";

				if( pages<=10 && pages>1 ){ //显示全部
					for(var i=1; i<=pages; i++){
						str += '<a href="'+ $.pwa.func.getHash(i, album_id) +'" onclick="'+ clickfun +'('+ i +', \''+ album_id +'\')"';
						if( page==i ){ str += ' class="pwa_nav_current" ';}
						str += '>'+ i +'</a> ';
					}
				}else if( pages>10 ){ //大于10页时，只显示首页，第一页，下一页，末页
					if( page>1 ){
						str += '<a href="'+ $.pwa.func.getHash(1, album_id) +'" onclick="'+ clickfun +'('+ 1 +', \''+ album_id +'\')">'+ navs[0] +'</a> ';
						str += '<a href="'+ $.pwa.func.getHash(page-1, album_id) +'" onclick="'+ clickfun +'('+ (page-1) +', \''+ album_id +'\')">'+ navs[1] +'</a> ';
					}
					if( page<pages ){
						str += '<a href="'+ $.pwa.func.getHash(page+1, album_id) +'" onclick="'+ clickfun +'('+ (page+1) +', \''+ album_id +'\')">'+ navs[2] +'</a> ';
						str += '<a href="'+ $.pwa.func.getHash(pages, album_id) +'" onclick="'+ clickfun +'('+ pages +', \''+ album_id +'\')">'+ navs[3] +'</a> ';
					}
					str += '<span>'+ navs[4].replace("{$1}", page).replace("{$2}", pages) +'</span>';
				}
				if( pages>1 ){
					return '<div class="pwa_nav"><p>' + str + '</p></div>';
				}
				return str;
			},
			
			album: function(item){ /* 获取相册列表 */
				str = '<div class="pwa_thumbnail">';
				str += '<p class="img"><a href="'+ $.pwa.func.getHash(1, item.gphoto$id.$t) +'" onclick="$.pwa.func.showPicList('+ 1 +',\''+ item.gphoto$id.$t +'\')">';
				str += '<img src="'+ item.media$group.media$thumbnail[0].url +'" alt="'+ item.summary.$t +'" /></a></p>';
				str += '<p class="info"><b class="title"><a href="'+ $.pwa.func.getHash(1, item.gphoto$id.$t);
				str += '" title="'+ ((item.summary.$t=="") ? "" : item.summary.$t + " - ") + $.pwa.defaults.lang.tit_tips_album + '" id="pwa_thumbnail_'+ item.gphoto$id.$t +'"';
				str += ' onclick="$.pwa.func.showPicList('+ 1 +',\''+ item.gphoto$id.$t +'\')">'+ item.title.$t +'('+ item.gphoto$numphotos.$t +')</a></b></p>';
				str += '</div>';
				return str;
			},
			
			piclist: function(item){ /* 获取照片列表 */
				str = '<div class="pwa_pics">';
				str += '<p class="img">'+ $.pwa.htmls.img("list", item.content.src, item.summary.$t) +'</p>';
				str += '<p class="info"><b class="title"><a href="'+ $.pwa.func.getHash(1, item.gphoto$albumid.$t, item.gphoto$id.$t) +'"';
				str += ' title="'+ ((item.summary.$t=="") ? "" : item.summary.$t + " - ") + $.pwa.defaults.lang.tit_tips_photo +'"';
				str += ' onclick="$.pwa.func.showPhoto('+ 1 +', \''+ item.gphoto$albumid.$t +'\', \''+ item.gphoto$id.$t +'\')">';
				str += ( (item.summary.$t=="") ? item.title.$t : item.summary.$t) +'</a></b><br/> ';
				str += '<span class="size">'+ $.pwa.func.getFormatSize(item.gphoto$size.$t) +'</span></p>';
				str += '</div>';
				return str;
			},
			
			photo: function(item){
				str = '<div class="pwa_album_photo_'+item.gphoto$id.$t+'">';
				str += '<p class="img">'+ $.pwa.htmls.img("photo", item.media$group.media$content[0].url, "「"+item.title.$t+"」" + item.subtitle.$t) +'</p>';
				str += '<h2>'+ item.title.$t +'</h2>';
				str += '<p class="info"><span class="subtit">'+ item.subtitle.$t +'</span><br/> ';
				str += '<span class="size">'+ $.pwa.func.getFormatSize(item.gphoto$size.$t) +"  "+ item.gphoto$width.$t+'*'+item.gphoto$height.$t+'</span></p>';
				str += '<p>'+ $.pwa.defaults.lang.exifs +'</p>';
				str += '<ul class="exif">';
				for(var p in item.exif$tags ){
					if( p == "exif$time" ){
						str += '<li>'+p.replace('exif$','')+': '+ $.pwa.func.getFormatDate( item.exif$tags[p].$t ) +'</li>';
					}else{
						str += '<li>'+p.replace('exif$','')+': '+ item.exif$tags[p].$t +'</li>';
					}
				}
				str += '</ul></div>';
				return str;
			}
		},
		/********************************************************************************/
		
		func: { /* functions */
			getIdByUrl: function(){ /* 获取url hash */
				hash = (!window.location.hash || window.location.hash=="#index") ? "#album,list,1,show" : window.location.hash; 
				args = hash.split(",");
				if( typeof(args[1]) == "undefined" ){ args[1]="list"; }
				if( typeof(args[2]) == "undefined" || args[2]=="" ||  (typeof(args[2])=="string" && parseInt(args[2])==0) ){
					args[2]=1; 
				}
				return args;
			},

			getHash: function(page, aid, pid){ /* 生成url hash */
				if( typeof(pid) != "undefined" ){ return "#photo,"+ aid + "," + page + "," + pid + ",show"; }
				if( typeof(aid) != "undefined" ){ return "#album,"+ aid + "," + page + ",show"; }
				return "#index";
			},
			
			getDom: function(tag, attr, content){ /* 生成dom标签 */
				var str = "";
				if( typeof(content) == 'undefined' ){ content="" ; }
				if( attr!="" && typeof(attr)=="object" ){
					for( var p in attr ){
						str += ' '+ p.replace('_','') + '="' + attr[p] + '"';
					}
				}
				if( content == null ){
					return '<' + tag + str + ' />';
				}
				return '<' + tag + str + '>' + content + '</' + tag + '>';
			},
			
			getUrl: function(page, aid, pid){ /* 生成json url */
				var str = offset = max_results = str_aid = str_pid = "";
				if( typeof(pid)!="undefined" ){
					str_pid = "/photoid/" + pid;
				}
				if( typeof(aid)!="undefined" && typeof(pid)=="undefined" ){
					str_aid = "/albumid/" + aid;
					offset = "&start-index=" + ( $.pwa.defaults.pagesize*(page-1)+1 ) ;
					max_results = "&max-results=" + $.pwa.defaults.pagesize;
				}
				str = 'https://picasaweb.google.com/data/feed/api/user/';
				str += $.pwa.defaults.userid + str_aid + str_pid + '?alt=json';
				str += offset + max_results + '&hl=zh_CN&mrasong&callback=?';
				return str;
			},
			
			getFormatSize: function(size){/* 格式化图片大小 */
				size = parseInt(size);
				if( Math.round(size*100/(1024*1024))/100 > 1.00 ){
					return Math.round(size*100/(1024*1024))/100 + " MB";
				}
				if( Math.round(size*100/1024)/100 > 1.00 ){
					return Math.round(size*100/1024)/100 + " KB";
				}
				return  size + " B";
			},
			
			getFormatDate: function(time){ /* 格式化时间 */
				var d = new Date(parseInt(time));
				return d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
			},
			
			goBack: function(aid, pid){ /* 返回主页 */
				$('.pwa_crumbs_photo').html('');
				$(".pwa_crumbs_album a").unbind('click');
				$('#pwa_album_photo').hide();
				
				if( typeof(pid)!="undefined" ){ //返回相册
					$('#pwa_album_'+aid).slideDown('slow');
					return false;		
				}
				
				$('.pwa_crumbs_album').html(''); //返回主页 
				$(".pwa_crumbs_index a").unbind('click');
				$('.pwa_crumbs').hide(); 
				$('#pwa_album_'+aid).slideUp('slow');
				$('#pwa_album_list').slideDown('slow');
				
			},
			
			goForward: function(aid, pid){ /* 显示列表 */
				$('#pwa_album_list').hide();
				if( typeof(pid)!="undefined" ){
					$('#pwa_album_'+aid).hide();
					$('#pwa_album_photo').slideDown('slow');
					return false;
				}
				
				$('.pwa_album_list').hide();
				$('#pwa_album_'+aid).slideDown('slow');
			},
			
			goTop: function (){ /* 回到顶部 */
				$("html, body").animate({ scrollTop: $.pwa.defaults.offset }, "slow");
			},
			
			tips: function(isshow){ /* 提示 */
				if( !$.pwa.defaults.tips ){
					var obj = {
						show: function(){ //显示加载提示
							$("#pwa_tips").fadeIn();
						},
						hide: function(){ //隐藏加载提示
							$("#pwa_tips").delay(800).fadeOut();
						}
					};
				}else{
					obj = $.pwa.defaults.tips;
				}
				if( isshow=="show" ){
					return obj.show();
				}else{ 
					return obj.hide(); 
				}
			},
			/********************************************************************************/
			
			showCrumbs: function(type, page, item){ /* 显示面包屑 */
				switch(type){
					case "photo":
						str = ' -&gt; <a href="'+$.pwa.func.getHash(1, item.gphoto$albumid.$t, item.gphoto$id.$t)+'" title="'+ item.title.$t + '">'+ item.title.$t +'</a>';
						$(".pwa_crumbs_photo").html(str);
						$(".pwa_crumbs_album a").bind({click: function(){ $.pwa.func.goBack( item.gphoto$albumid.$t, item.gphoto$id.$t );} });
						break;
					case "photo_cache":
						str = ' -&gt; <a href="'+$.pwa.func.getHash(1, item.aid, item.pid)+'" title="'+ item.title + '">'+ item.title +'</a>';
						$(".pwa_crumbs_album a").bind({click: function(){ $.pwa.func.goBack( item.aid, item.pid );} });
						$(".pwa_crumbs_photo").html(str);
						break;
					case "album":
						str = ' -&gt; <a href="'+$.pwa.func.getHash(page, item.gphoto$id.$t)+'" title="'+ item.title.$t + '">'+ item.title.$t +'(' +item.gphoto$numphotos.$t+ ')</a>';
						$(".pwa_crumbs_photo").html('');
						$(".pwa_crumbs_album").html(str);
						$(".pwa_crumbs_index a").bind({click: function(){ $.pwa.func.goBack(item.gphoto$id.$t);} });
						$(".pwa_crumbs").show();
						break;
					case "album_cache":
						$(".pwa_crumbs_photo").html('');
						$(".pwa_crumbs_index").html('<a href="'+$.pwa.func.getHash(1)+'" onclick="$.pwa.func.goBack(\''+item.id+'\')">'+$.pwa.defaults.lang.home+'</a>');
						$(".pwa_crumbs_album").html(item.html);
						$(".pwa_crumbs").show();
						break;
					default:
						str = '<a href="'+$.pwa.func.getHash(1)+'">'+$.pwa.defaults.lang.home+'</a>';
						$(".pwa_crumbs_photo").html('');
						$(".pwa_crumbs_album").html('');
						$(".pwa_crumbs_index").html(str);
						$(".pwa_crumbs").hide();
						break;
				}
			},
			
			showAlbum: function(){ /* 显示相册列表 */
				$.pwa.func.goTop();//返回顶部
				$.pwa.func.tips("show");//显示提示
				
				$.pwa.func.showCrumbs('index', 1); //显示当前位置
				$.getJSON($.pwa.func.getUrl(1), function(d){ //加载数据

					$.each(d.feed.entry, function(i, item){
						$('#pwa_album_list').append( $.pwa.htmls.album(item) );
						$('#pwa_content').append(
							$.pwa.func.getDom('div', { _id:'pwa_album_'+item.gphoto$id.$t, _class:'pwa_album_list', _cpage:'-1', _style:'display:none;' }) 
						);
					});
					$('#pwa_album_list').append( $.pwa.htmls.clear() );
					
					$.pwa.func.tips("hide");//隐藏提示
				});
			},
			
			showPicList: function(page, aid){ /* 图片列表 */
				$.pwa.func.goTop(); //scroll to top
				
				if( $('#pwa_album_'+aid).attr("cpage")!=page ){ //if not cached
					$.pwa.func.tips("show"); //show loading tips
					$.getJSON($.pwa.func.getUrl(page, aid), function(d){
						if( !d.feed.entry ){ $.pwa.func.tips("hide"); return false; }
						$.pwa.func.goForward(aid); //hide index list & show cached album list
						$.pwa.func.showCrumbs('album', page, d.feed); //show where you are now

						$('#pwa_album_'+aid).html("");
						$('#pwa_album_'+aid).attr("cpage", page);
						
						$.each(d.feed.entry, function( i, item ){
							$('#pwa_album_'+aid).append( $.pwa.htmls.piclist(item) );
						});
						$('#pwa_album_'+aid).append( $.pwa.htmls.clear() );
						$('#pwa_album_'+aid).append( $.pwa.htmls.nav(d.feed, page) ); //show the navigation
						$('#pwa_album_'+aid).append( $.pwa.func.getDom('div', { _class:'pwa_crumb', _style:'display:none;' }, $('.pwa_crumbs_album').html() ) );//temp html
						
						$.pwa.func.tips("hide");//hide the loading tips
					});
				}else{
					$.pwa.func.goForward(aid); //hide index list & show cached album list
					$.pwa.func.showCrumbs('album_cache', page, { id:aid, html:$('#pwa_album_'+aid+' .pwa_crumb').html() }); //显示当前位置
				}
			},
			showPhoto: function(page, aid, pid){
				$.pwa.func.goTop();

				if( !$('.pwa_album_photo_'+pid).html() ){
					$.pwa.func.tips("show");
					$.getJSON($.pwa.func.getUrl(page, aid, pid), function(d){
						if( !d.feed ){ $.pwa.func.tips("hide"); return false; }
						
						$.pwa.func.goForward(aid, pid); //hide the album list & show the single photo
						$.pwa.func.showCrumbs('photo', 1, d.feed); //show where you are now
						$("#pwa_album_photo").html( $.pwa.htmls.photo(d.feed) ); //show photo data
						
						$.pwa.func.tips("hide");
					});
				}else{ 
					$.pwa.func.goForward(aid, pid); //hide the album list & show the single photo
					$.pwa.func.showCrumbs('photo_cache', page, {aid:aid, pid:pid, title:$('.pwa_album_photo_'+pid+' h2').html()} ); //show where you are now
				}
			}
		},
		/********************************************************************************/

		init: function(obj){ /* initialization */
			if( typeof(obj)=="object" ){ $.extend($.pwa.defaults, obj); } //extend defaults
			if( !$("#"+$.pwa.defaults.showid) ){ //add a div tag if not exist
				$("body").append( $.pwa.func.getDom('div', { _id:$.pwa.defaults.showid }) );
			}
			$('#'+$.pwa.defaults.showid).html( $.pwa.htmls.wrap() );
			$.pwa.func.showAlbum();
			var args = $.pwa.func.getIdByUrl(); //get arguments by url hash
			if( args && args[1]!="list" ){ //show album by aid
				$.pwa.func.showPicList(args[2], args[1]);
				if( typeof(args[3])!="undefined" && args[3]!="show" ){ //show photo by pid
					$.pwa.func.showPhoto(args[2], args[1], args[3]);
				}
			}
		}
	}
});
}(jQuery));